package com.infinit.easyreader.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.infinit.easyreader.Biz.RankContentBiz;
import com.infinit.easyreader.R;
import com.infinit.easyreader.adpter.RankRecylerAdapter;
import com.infinit.easyreader.dao.RankDao;
import com.infinit.easyreader.entity.RankContent;
import com.infinit.easyreader.entity.RankTime;
import com.infinit.easyreader.ui.BookContentActivity;
import com.infinit.easyreader.utils.Consts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 类：com.infinit.easyreader.fragment.RankListFragment V[1.0.0]
 * 作用：显示排行榜列表
 * Created by rzy on 2016/7/1.
 */
public class RankListFragment extends Fragment implements Consts {


    public static final String INTENT_CONTENT = "contentIntent";
    @Bind(R.id.lvRankList)
    RecyclerView lvRankList;
    @Bind(R.id.srlRankContent)
    SwipeRefreshLayout srlRankContent;
    private int count = 15;
    private List<RankContent> contents;
    private RankRecylerAdapter rlAdapter;
    private int start = 0;
    private String rankTimeId;
    private Handler handler;
    private LinearLayoutManager mManager;
    private boolean isAdd = false;

    public void setStart(int start) {
        this.start = start;
    }

    public void setCount(int count) {
        this.count = count;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_ranklist, container, false);
        ButterKnife.bind(this, v);

        Bundle bundle = getArguments();
        String rankTimeName = bundle.getString(CloudFragment.RANK_TIME_NAME);
        handler = new Handler(new Handler.Callback() {
            @SuppressWarnings("unchecked")
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case RankContentBiz.CODE_RANKCONTENT_SUCCESS:
                        //设置ListView的适配器
                        contents = (List<RankContent>) msg.obj;
                        if (!isAdd) {
                            rlAdapter.setData(contents);
                            rlAdapter.notifyDataSetChanged();
                            srlRankContent.setRefreshing(false);
                        } else {
                            rlAdapter.addMoreData(contents);
                            rlAdapter.setLoad_status(RankRecylerAdapter.LOAD_STATUS_TO_LOAD);
                        }

                        break;
                    case RankContentBiz.CODE_RANKCONTENT_FAIL:
                        Toast.makeText(getActivity(), "获取排行信息失败,请稍后再试!", Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
        RankDao rankDao = new RankDao(getActivity());
        RankTime rankTime = rankDao.getRankTime(rankTimeName);
        rankTimeId = rankTime.getRankTimeID() + "";
        rankDao.close();
        accessInternet();
        setAdapter();
        setListeners();
        return v;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 设置适配器
     */
    private void setAdapter() {
        contents = new ArrayList<>();
        rlAdapter = new RankRecylerAdapter(contents);
        lvRankList.setAdapter(rlAdapter);
        mManager = new LinearLayoutManager(getActivity());
        mManager.setOrientation(LinearLayoutManager.VERTICAL);
        lvRankList.setLayoutManager(mManager);
    }

    /**
     * 设置监听器
     */

    @SuppressWarnings("deprecation")
    private void setListeners() {
        srlRankContent.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //更新数据
                start = 0;
                accessInternet();
                isAdd = false;
            }

        });

        /**
         * 设置RecyclerView的Listener
         */

        lvRankList.setOnScrollListener(new RecyclerView.OnScrollListener() {

            private int lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

                if (newState == RecyclerView.SCROLL_STATE_IDLE && rlAdapter.getItemCount() == lastVisibleItem + 1) {
                    rlAdapter.setLoad_status(RankRecylerAdapter.LOAD_STATUS_LOADING);
                    //加载数据
                    start = lastVisibleItem + 1;
                    accessInternet();
                    isAdd = true;
                }
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mManager.findLastVisibleItemPosition();
            }
        });


        /**
         * 为RecyclerView设置监听器
         */

        rlAdapter.setOnItemClickListener(new RankRecylerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Log.d(TAG, "onItemClick: 当前点击的位置为:" + position);
                if (contents.size() != 0) {
                    RankContent content = contents.get(position);
                    Intent intent = new Intent(getActivity(), BookContentActivity.class);
                    Log.d(TAG, "onItemClick: " + content.getWapURL());
                    intent.putExtra(INTENT_CONTENT, content);
                    startActivity(intent);

                }

            }
        });



    }

    /**
     * 从互联网获取排行数据
     */


    private void accessInternet() {
        //获取RankNameId

        Map<String, String> params = new HashMap<>();
        int rankTypeId = 1;
        params.put("rankType", rankTypeId + "");
        int contentTypeId = 1;
        params.put("contentType", contentTypeId + "");
        params.put("rankTime", rankTimeId);
        params.put("start", start + "");
        RankContentBiz rankContentBiz = new RankContentBiz(handler, getActivity());
        rankContentBiz.setParams(params);
        rankContentBiz.setCount(count);
        rankContentBiz.getRankContentFromInternet();
    }
}
